package controllers;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import play.libs.Json;
import models.Booking;
import models.Dispatch;
import models.statistic.StatisticMainModel;
import play.mvc.*;;

public class StatisticMain extends Controller {
	public static Result get() {
		StatisticMainModel model = calculateStatistic();		
		return ok(Json.toJson(model));
	}
	
	public static StatisticMainModel calculateStatistic() {
		int ONE_DAY_IN_MILLISECONDS = 86400000;
		StatisticMainModel model = new StatisticMainModel();
		
		//today
		Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
		
		Calendar firstTimeToday = (Calendar) now.clone();
		firstTimeToday.set(Calendar.MILLISECOND, 0);
		firstTimeToday.set(Calendar.HOUR_OF_DAY, 0);
		firstTimeToday.set(Calendar.MINUTE, 0);
		firstTimeToday.set(Calendar.SECOND, 0);
		
		Calendar lastTimeToday = (Calendar) firstTimeToday.clone();
		lastTimeToday.add(Calendar.MILLISECOND, ONE_DAY_IN_MILLISECONDS-1);

		List<Booking> listBook = Booking.find.where().between("start_date", firstTimeToday.getTime(), lastTimeToday.getTime()).findList();
		int booked = listBook.size();
		int unScheduled = 0;
		//TODO: performance issue
		for(int i=0; i<booked; i++)
		{
			if (Dispatch.find.where().eq("book_id", listBook.get(i).id.intValue()).findRowCount() == 0) {
				unScheduled++;
			}
		}
		model.setUnscheduleVehiclesToday(unScheduled);
		model.setScheduledVehiclesToday(booked);
		if (booked == 0) {
			model.setScheduledRateToday(0.0);
		} else {
			model.setScheduledRateToday((double)(booked-unScheduled)/(double)(booked));
		}
		
		//this month
		Calendar firstTimeOfMonth = (Calendar) firstTimeToday.clone();
		firstTimeOfMonth.set(Calendar.DATE, 1);
		
		List<Booking> listBookThisMonth = Booking.find.where().between("start_date", firstTimeOfMonth.getTime(), now.getTime()).findList();
		int bookedThisMonth = listBookThisMonth.size();
		int unScheduledThisMonth = 0;
		for(int i=0; i<bookedThisMonth; i++)
		{
			if (Dispatch.find.where().eq("book_id", listBookThisMonth.get(i).id).findRowCount() == 0) {
				unScheduledThisMonth++;
			}
		}
		model.setScheduledVehiclesMonth(bookedThisMonth);
		model.setUnscheduledVehiclesMonth(unScheduledThisMonth);
		if (bookedThisMonth == 0) {
			model.setScheduledRateToday(0.0);
		} else {
			model.setScheduledRateToday((double)(bookedThisMonth-unScheduledThisMonth)/(double)(bookedThisMonth));
		}
		
		return model;
	}
}
